/*
*
* 附件上传接口
*/

"use strict"

const uploadUnit = require('../../util/Upload');
const express = require('express');
const router = express.Router();
const path = require('path');

const multer  = require('multer');


const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'images');
    },
    filename: function (req, file, cb) {
        cb(null, Date.now()+'_'+file.originalname);
    }
})

const upload = multer({ storage: storage });


router.get('/', (req,res) => {
    res.json ([
            {
                title: '附件上传接口',
                api:'api/upload/file',
                post:'post',
                Header:'Content-Type:multipart/form-data',
                return:'filePath：附件的名称'
            },
            {
                title: '附件获取',
                api:'api/upload/file/:id',
                post:'get',
                exp:'http://token.asuscomm.com:8089/api/upload/file/1577523224692_mongodb-osx-ssl-x86_64-4.0.9.tgz'
            }
    ]);
});

/**
 * [add] /file
 * 上传图片
 * @param {*} 任意名字
 *
 */
router.post('/file', upload.any(), (req,res) => {
    res.send({
        filePath: path.basename(req.files[0].path),
        status:2,
        msg:'上传成功'
    })
});

/**
 * [get] /img
 *  附件查看 上传附件返回的地址  http://localhost:5000/api/upload/img/1547523883422_2018-09-12_en-US.jpg
 */
router.get('/file/:id',  (req,res) => {
    res.sendFile(path.resolve(`./images/${req.params.id}`))
});
module.exports = router;
